﻿Partial Public Class REST
    Private mAuth As Authorization
    Public ReadOnly Property Auth As Authorization
        Get
            Return mAuth
        End Get
    End Property


    Public Class Authorization
        Private mRest As REST
        Public ReadOnly Property REST As REST
            Get
                Return mRest
            End Get
        End Property

        Public Property Application As lfm.Application
        Friend Sub New(ByVal App As lfm.Application, ByVal restClass As lfm.REST)
            Me.Application = App
            Me.mRest = restClass
        End Sub

        ''' <summary>
        ''' Send a request to auth.getMobileSession, sending the user's credentials to the call.
        ''' </summary>
        ''' <param name="username">Last.fm username</param>
        ''' <param name="password">Last.fm password</param>
        ''' <returns>A <see cref="UserSession">UserSession</see> object.</returns>
        Public Function getMobileSession(ByVal username As String, ByVal password As String) As lfm.UserInfo
            username = username.ToLowerInvariant
            Dim authToken As String = GenerateHashDigest(username + GenerateHashDigest(password, HashMethod.MD5), HashMethod.MD5)
            Dim answer As XDocument = Me.REST.ExecuteRest("auth.getMobileSession",
                                                          {
                                                              {"username", username},
                                                              {"authToken", authToken}
                                                          }, True)

            Dim status As String = answer.<lfm>.@status

            If status = "error" Then
                Return Nothing
            End If

            Dim UserSession As New UserInfo With {
                .Name = answer.<lfm>.<session>.<name>.Value,
                .Key = answer.<lfm>.<session>.<key>.Value,
                .Subscriber = Not (answer.<lfm>.<session>.<subscriber>.Value = "0"),
                .IsAuthenticated = True
            }
            Me.REST.UserSession = UserSession
            Return UserSession
        End Function

        ''' <summary>
        ''' Fetch an unathorized request token for an API account. This is step 2 of the authentication process for desktop applications. Web applications do not need to use this service.
        ''' </summary>
        ''' <returns>token</returns>
        Public Function getToken() As String
            Dim answer As XDocument =
                Me.REST.ExecuteRest("auth.getToken", , True)

            If answer.<lfm>.@status = "error" Then
                Return ""
            End If

            Return answer.<lfm>.<token>.Value
        End Function
   
    End Class

End Class